package sgi.client;

import java.io.IOException;

import sgi.message.Message;
import sgi.message.MessageLogin;
import sgi.message.MessageLogoff;
import sgi.message.MessagePrompt;
import sgi.user.User;

public class SGILoginController extends SGIController {
	
	private static SGILoginUI loginUI;
	private SGIClientConnectionController connection;
	private static SGILoginController login;
	
	public static SGILoginController createLogin() throws IOException
	{
		if(login == null)
		{
			login = new SGILoginController(SGIClientConnectionController.createConnection());
			loginUI.setLoginController(login);
		}
		loginUI.setVisible(true);
		return login;
	}
	
	public static void terminate()
	{
		SGILoginController.loginUI.setVisible(false);
		SGILoginController.loginUI=null;
		SGILoginController.login=null;
	}
	
	private SGILoginController(SGIClientConnectionController connection)
	{
		this.connection = connection;
		setLoginUI(new SGILoginUI());
	}
	
	
	public void handleMessageFromLoginUI(String username,String password) throws IOException
	{
		MessageLogin msg = new MessageLogin(username,password);
	    try
	    {
	    	connection= SGIClientConnectionController.createConnection();
	    	connection.handleMessageFromClientUI(msg);
	    } catch(IOException e) { loginUI.setNotification("Communication with the server failed!"); throw e;}
	}
	
	void setLoginUI(SGILoginUI loginUI)
	{
		SGILoginController.loginUI=loginUI;
	}
	
	@Override
	void handleMessage(Object msg) {
		if(((MessageLogin)msg).getLoginSucceeded() == true)
		{
			User user = new User(((MessageLogin)msg).getUsername(),((MessageLogin)msg).getPassword(),((MessageLogin)msg).getPrivilege());
			switch(user.getPrivilege())
			{
				case 1:
					SGIUserAccountMenuController.create(user);
					break;
			}
			loginUI.setVisible(false);
		}
		else
		{
			loginUI.setNotification("Login failed! Check username and password and try again.");
		}
	}

	public void logoff(User user) throws IOException
	{
		/*Create login query to update userOnline status*/
		MessageLogoff msga = new MessageLogoff(user.getUsername(),user.getPassword());
		MessagePrompt msgb = new MessagePrompt(user.getUsername() + " logged off.");
		try {
			  connection=SGIClientConnectionController.createConnection();
			  connection.handleMessageFromClientUI(msga);
			  connection.handleMessageFromClientUI(msgb);
			  SGIUserAccountMenuController.resetMenu();
		} catch (IOException e) {throw e;}
	}
}
